package umn.monopolybankservice

import grails.converters.JSON

class GameController {

    def show = {
        if(params.id && Game.exists(params.id)) {
            render Game.findById(params.id).getJsonString()
        }
        else {
            render Game.list() as JSON
        }

    }

    def findGame = {
        Game game = Game.findByName(params.gameName)
        if (game) {
            render game.getJsonString()
        }
        else {
            render '{"error":"game not found"}'
        }
    }

    def save = {
        def game = new Game(params['game'])
        if (game.save()) {
            render game.getJsonString()
        }
        else {
            //handle errors
        }
    }

    def update = {
        if(params.id && Game.exists(params.id)) {

        }
        else {

        }
    }

    def createGame = {

        //def json = JSON.parse(request)

        Game game = new Game()
        //game.setName(json['gameName'])
        game.name = params.gameName
        game.startMoney = Double.parseDouble(params.startMoney.toString())
        game.save(flush: true)
        Player player = new Player()
        //player.setName(json['playerName'])
        player.setName(params.playerName)
        player.isGameCreator = true
        player.setGame(game)
        //double wallet = Double.parseDouble(json['wallet'])
        double wallet = Double.parseDouble(params.startMoney.toString())
        player.setWallet(wallet)
        player.save(flush: true)

        Player bank = new Player()
        bank.setGame(game)
        bank.setName("Bank")
        bank.setWallet(100)
        bank.save(flush: true)
        game.refresh()
        response.setStatus(201)
        response.setHeader("Location","/game/" + game.id)
        render game.getJsonString()
    }

    def remove = {
        if(params.id && Game.exists(params.id)) {

        }
        else {

        }
    }
}

